package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.basic.vo.NccBasicBillsTypeTree;
import com.bzkj.basicinfo.domain.ncc.NccBasicBillsType;
import com.bzkj.basicinfo.domain.ncc.erp.BillTypeBean;
import com.bzkj.basicinfo.mapper.NccBasicBillsTypeMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicBillsTypeService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

/**
 * 单据类型：10
 */
@Service("nccJobBillsTypeService")
public class NccBasicBillsTypeServiceImpl implements NccBasicBillsTypeService
{
    @Value("${ncc.baseUrl}")
    private  String baseUrl;

    @Value("${ncc.basicInfoUrl}")
    private String baseInfoUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;


    @Autowired
    private NccBasicBillsTypeMapper nccBasicBillsTypeMapper;
    @Autowired
    private NccBasicUtil nccBasicUtil;

    @Override
    public void updateNccBasicBillsTypeJob(String all)
    {
        if("all".equals(all)) {
            nccBasicUtil.ncc(10, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(10);
            if(response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicBillsType> basicBillsTypes = dataArray.toList(NccBasicBillsType.class);
                for(NccBasicBillsType basicBillsType : basicBillsTypes) {
                    NccBasicBillsType basicCustomer1 = nccBasicBillsTypeMapper.queryNccBasicBillsType(basicBillsType.getNodeCode());
                    if(basicCustomer1 != null) {
                        nccBasicBillsTypeMapper.updateNccBasicBillsType(basicBillsType);
                    } else {
                        nccBasicBillsTypeMapper.insertNccBasicBillsType(basicBillsType);
                    }
                }
            }
        }
    }

    @Autowired
    private HttpClientUtils hcu;

    /**
     * 同步当天类型信息
     *
     * @return
     */
    @Override
    public R jobMethod(Boolean flag)
    {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute("2024-05-20 02:32:20", "2024-05-29 02:32:20",10, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<BillTypeBean> list = jsonNode.getJSONArray("data").toJavaList(BillTypeBean.class);
        if(! list.isEmpty())
            extracted(list);

        return R.ok("同步成功");
    }

    @Override
    public R findWmsUseBillsTypeAll()
    {
        List<NccBasicBillsTypeTree> type = nccBasicBillsTypeMapper.findAllBasicBillsType();
        return R.ok(type);
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<BillTypeBean> list)
    {
        for (BillTypeBean billTypeBean : list) {
            nccBasicBillsTypeMapper.insertOrUpdate(billTypeBean);
        }
    }

    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i)
    {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(baseInfoUrl)
                .header("sourceSystem", sourceSystem)
                .header("targetSystem", targetSystem)
                .header("serviceName", serviceName)
                .header("contentType", contentType)
                .body(jsonString, "application/json")
                .execute();
        return response;
    }
}
